package zy928;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//以products.xml作为基础，实现客户购买的方法，输入商品号和购买数量，计算应付金额，
//如果是折扣商品，打七折；如果购买数量超过库存量，给出提示；
//商品不存在，给出提示；购买成功，扣除相应的数量。最后输出应付款的金额。
public class Zy4 {
	public static void main(String[] args) throws DocumentException, IOException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("products.xml"));
		Scanner in = new Scanner(System.in);
		List<Element> list = doc.selectNodes("shop/product");

		System.out.println("请输入商品号");
		String s = in.next();
		System.out.println("请输入购买数量");
		int i = in.nextInt();
		for (Element e : list) {
			if (i > Integer.parseInt(e.selectSingleNode("stockcount").getText())) {
				System.out.println("你买的太多了  缺货");
				return;
			}
			// boolean v = Boolean.parseBoolean(e.selectSingleNode("discount").getText());
			if (e.attributeValue("discount").equals("true")) {// 可以打折
				double price = Double.parseDouble(e.selectSingleNode("price").getText());
				int num2 = Integer.parseInt(e.selectSingleNode("stockcount").getText());
				// int num3 = num2 - i;
				int sum = 0;
				sum = (int) (price * i * 0.7);
				System.out.println("花了" + sum + "钱");
				e.selectSingleNode("stockcount").setText((num2 - i) + "");
				break;
			} else if (e.attributeValue("discount").equals("false")) {
				double price = Double.parseDouble(e.selectSingleNode("price").getText());
				int num2 = Integer.parseInt(e.selectSingleNode("stockcount").getText());
				// int num3 = num2 - i;
				int sum = 0;
				sum = (int) (price * i);
				System.out.println("花了" + sum + "钱");
				e.selectSingleNode("stockcount").setText((num2 - i) + "");
				break;
			}

		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter xm = new XMLWriter(new FileWriter("products.xml"), format);
		xm.write(doc);
		System.out.println("写入成功");
		xm.close();
	}
}
